import fastify from 'fastify';
import cors from '@fastify/cors';
import {addSellBill, getSellBill} from "./sqlite.js";

const app = fastify({logger: true},);
const apiFix = "/api"
console.log(cors)

app.register(cors, {
    origin: '*', // 允许所有域名访问
    methods: ['GET', 'POST', 'PUT', 'DELETE'], // 允许的 HTTP 方法
    allowedHeaders: ['Content-Type', 'Authorization'], // 允许的请求头
    credentials: true, // 允许发送凭据（如 cookies）
});

app.get('/', async (request, reply) => {
    return "Hello World111111111!"
});

// 接收数据
app.post(apiFix + '/user/receive_data', async (request, reply) => {
    const data = request.body;

    console.log('12212222222222',addSellBill(data))
    if (!data) {

        return reply.status(400).send({message: '未接收到有效数据'});
    }
    try {
        await data;
        return reply.send({message: '数据接收成功'});

    } catch (error) {
        console.error(`Error: ${error}`);
        return reply.status(500).send({message: '数据处理失败'});
    }
});


// 获取数据
app.get(apiFix + '/user/get_data'   , async (request, reply) => {
    console.log(9898)
    let kkk = await getSellBill()
    console.log(kkk)
    return kkk
});

// 启动服务器
const start = async () => {
    try {
        await app.listen({port: 5001, host: '127.0.0.1'});
        app.log.info(`Server listening on http://localhost:5001`);
    } catch (err) {
        app.log.error(err);
        process.exit(1);
    }
};

start();